

(function ($, win, doc, body) {
    var supportedClient = true,
        jqTemplateId = "jqTemplateButtonGroup",
        openedClassname = "tl-btngroup-opened",
        disabledClassname = "disabled",
        $body = $(body);

    // check client
    supportedClient = true;

    // callbacks
    function onBodyClick (evt) {
        $body.unbind("click", onBodyClick).find("div." + openedClassname)
          .removeClass(openedClassname).find("div.menu-container").hide();
    }

    function onTitleClick (evt) {
        onBodyClick();
        var $btngroup = $(this).parents('div.btn-group:first');

        if ($btngroup.hasClass(openedClassname) || $btngroup.hasClass(disabledClassname)) {
          return undefined;
        }

        $btngroup.addClass(openedClassname).find("div.menu-container:first").show();
        setTimeout(bindBodyEvents, 0);
    }

    function bindBodyEvents () {
        $body.bind("click", onBodyClick);
    }

    function bindEvents ($btngroup) {
        $btngroup.children("button.btn:first")
          .bind("click", onTitleClick);
    }

    function initButtonGroup ($btnTitle, $btns) {
        var $btngroup,
            classname = "",
            btnTitleClasses = ($btnTitle.attr("class") || "").split(/\s+/),
            btnTitleClassesInd = 0,
            incorrectClasses = ["btn", "border-radius"],
            incorrectClassesInd = 0,
            data = {
                classname: ""
            };

        incorrectClassesInd = incorrectClasses.length;
        while (incorrectClassesInd--) {
            classname = incorrectClasses[incorrectClassesInd];
            btnTitleClassesInd = btnTitleClasses.length;
            while (btnTitleClassesInd--) {
                if (classname == btnTitleClasses[btnTitleClassesInd]) {
                    btnTitleClasses.splice(btnTitleClassesInd, 1);
                    break;
                }
            }
        }
        data.classname = btnTitleClasses.join(" ");

        $btngroup = $.tlTmpl(jqTemplateId, data);
        $btnTitle.before($btngroup);
        $btngroup.append($btnTitle);
        $btngroup.find("div.menu-list:first").append($btns);

        bindEvents($btngroup);
    }

    $.fn.tlButtonGroup = function (selector) {
        if (supportedClient && this.is('button')) {
            initButtonGroup(this.filter(":first"), $(selector));
        }

        return this;
    };
})(jQuery, window, document, document.body);
